package com.von.nhcf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.von.nhcf.constant.AccessIgnoreResources;
import com.von.nhcf.constant.NhcfConstant;
import com.von.nhcf.entity.vo.MemberLoginVO;
import com.von.nhcf.exception.AccessIllegalException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class NhcfAccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //获取servletPath
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String servletPath = request.getServletPath();
        // 判断servletPath是否为需要拦截的url资源
        if (AccessIgnoreResources.PASS_RES_SET.contains(servletPath)) {
            return false;
        }
        // 判断servletPath是否为需要拦截的静态资源
        return !AccessIgnoreResources.judgeCurrentServletPath(servletPath);
    }

    @Override
    public Object run() {
        // 获取request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 获取当前的session值，判断当前用户是否登录
        HttpSession session = request.getSession();
        // 获取session中的当前用户对象
        MemberLoginVO member = (MemberLoginVO) session.getAttribute(NhcfConstant.ATTR_NAME_MEMBER);
        if (member == null) {
            // 将未登录的提示信息存入session域中
            session.setAttribute(NhcfConstant.ATTR_MESSAGE_NAME, NhcfConstant.MESSAGE_ACCESS_ILLEGAL);
            // 重定向的登录页面
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.sendRedirect("/member/auth/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
